<template>
	<view class="">
		<template v-if="isMount">
			<form0 v-show="current === 0" ref="form0Ref" />
			<form1 v-show="current === 1" ref="form1Ref" />
			<form2 v-show="current === 2" ref="form2Ref" />
			<form3 v-show="current === 3" ref="form3Ref" />
		</template>

		<view class="fixed-bottom-placeholder">
			<view class="" style="height: 144rpx"></view>
			<fui-safe-area background="#f2f2f2"></fui-safe-area>
		</view>
		<view class="fixed-bottom">
			<view class="fs-flex fs-justify__between fs-px32 fs-py24">
				<view class="" style="width: 45%">
					<fui-button @click="handlePrevious" type="warning" dis :disabled="current === 0"
						disabledBackground="rgba(0,0,0,0.1)"
						background="linear-gradient(141.96deg, #7d63ff 0%, #d269ff 100%)">
						上一页
					</fui-button>
				</view>
				<view v-if="current < 3" class="" style="width: 45%">
					<fui-button @click="handleNext" type="warning"
						background="linear-gradient(141.96deg, #d269ff 0%, #7d63ff 100%)">下一页</fui-button>
				</view>
				<view v-else class="" style="width: 45%">
					<fui-button @click="handleNext" type="warning"
						background="linear-gradient(141.96deg, #d269ff 0%, #7d63ff 100%)">提交</fui-button>
				</view>
			</view>
			<fui-safe-area background="#f2f2f2"></fui-safe-area>
		</view>

		<fui-landscape :show="show" :closable="true" position="3" @close="closePopup" :z-index="99999">
			<view class="fui-ani__box">
				<image class="fui-hd__img" src="/static/success-bg.png" mode="widthFix"></image>
				<view class="fui-box-content fui-flex__center fui-flex__column">
					<view v-if="!id" class="fui-ani__title">恭喜！报单成功！</view>
					<view v-else class="fui-ani__title">恭喜！编辑报单成功！</view>
					<view class="fui-desc">{{ successMsg }}</view>
					<fui-button btn-size="medium" radius="100rpx"
						background="linear-gradient(180deg, #E3BF82 0%, #997B4A 100%)" borderColor="rgba(0,0,0,0)"
						border-width="0" @click="btnClick">
						一键复制
					</fui-button>
				</view>
			</view>
		</fui-landscape>

		<fui-load-ani v-if="loading" type="3" isFixed maskColor="rgba(0,0,0,0.1)"></fui-load-ani>
	</view>
</template>

<script setup>
	import { onMounted, provide, ref, getCurrentInstance } from 'vue';
	import form0 from './form0.vue';
	import form1 from './form1.vue';
	import form2 from './form2.vue';
	import form3 from './form3.vue';
	import { submitReportingForm, submitEditForm, fetchDetail, fetchCopyInfo } from '@/common/api/index.js';
	import { onLoad, onShareAppMessage } from '@dcloudio/uni-app';
	import { useUserStore } from '../../stores/user';

	const show = ref(false);

	function closePopup() {
		show.value = false;
		uni.navigateBack();
	}

	async function btnClick() {
		const res = await fetchCopyInfo(successId.value);
		if (res) {
			uni.setClipboardData({
				data: res,
				success: function() {
					uni.$fui.toast('复制成功');
					setTimeout(() => {
						closePopup();
						uni.navigateBack();
					}, 1500);
				}
			});
		}
	}

	const { userinfo } = useUserStore();

	const current = ref(0);
	const loading = ref(false);
	const formData = ref({
		city_id: userinfo ? userinfo.city_id : '',
		department_id: userinfo ? userinfo.department_id : '',
		team: '',
		sign_person: userinfo ? userinfo.name : '',
		sign_date: '',
		channel_id: '',

		customer_type: '',
		company_name: '',
		customer_name: '',
		customer_category: '',

		products: [{
			product_type: '',
			product_subdivision: '',
			actual_payment: '',
			account_start_date: '',
			agency_start_month: '',
			agency_end_month: '',
			agency_months: '',
			register_region: '',
			is_urgent: '',
			cost: {
				kezhang_chengben: '',
				baoshui_ruanjian: '',
				shuzi_zhengshu: '',
				qudao_chengben: '',
				yuanqu_dizhi: '',
				jiaji_feiyong: ''
			},
			profit: {
				qita_shouru: '',
				zhuce_shouru: '',
				yuanqu_zhuce: '',
				zhuxiao_shouru: '',
				gaoduan_shouru: '',
				waibao_shouru: '',
				zizhi_shouru: '',
				daizhang_feiyong: '',
				kezhang_maoli: '',
				shebao_gongjijin: ''
			}
		}],

		support_renew_id: '',
		service_detail: '',
		payment_way: '',
		remark: ''
	});

	provide('formData', formData);
	const form0Ref = ref(null);
	const form1Ref = ref(null);
	const form2Ref = ref(null);
	const form3Ref = ref(null);

	function handlePrevious() {
		current.value--;
	}

	async function handleNext() {
		if (current.value === 0) {
			const res = await form0Ref.value.submit();
			if (!res.isPassed) return;
		} else if (current.value === 1) {
			const res = await form1Ref.value.submit();
			if (!res.isPassed) return;
		}
		if (current.value === 2) {
			const res = await form2Ref.value.submit();
			if (!res.isPassed) return;
		}
		if (current.value === 3) {
			const res = await form3Ref.value.submit();
			if (!res.isPassed) return;
			handleSubmit();
			return;
		}

		current.value++;
	}

	const eventChannel = ref(null)
	onMounted(() => {
		const instance = getCurrentInstance().proxy
		eventChannel.value = instance.getOpenerEventChannel();
	})

	const successMsg = ref('');
	const successId = ref('');
	async function handleSubmit() {
		let { customer_type, support_renew_id, products, ...rest } = formData.value;
		products = products.map((item) => {
			const {
				costTotal,
				profitTotal,
				grossTotal,
				agency_months,
				is_urgent,
				cost,
				profit,
				customer_type,
				support_renew_id,
				...reset
			} = item;
			for (let key in cost) {
				cost[key] = !cost[key] ? 0 : cost[key];
			}
			for (let key in profit) {
				profit[key] = !profit[key] ? 0 : profit[key];
			}
			return {
				agency_months: !agency_months ? 0 : agency_months,
				is_urgent: !is_urgent ? 0 : is_urgent,
				cost: { ...cost },
				profit: { ...profit },
				...reset
			};
		});
		const p = {
			...rest,
			products,
			customer_type: !customer_type ? 0 : customer_type,
			support_renew_id: !support_renew_id ? 0 : support_renew_id
		};

		loading.value = true;
		let res;
		if (!id.value) {
			res = await submitReportingForm(p).catch(() => {
				loading.value = false;
			});
		} else {
			res = await submitEditForm(id.value, p).catch(() => {
				loading.value = false;
			});
		}

		if (res.code === 200) {
			successMsg.value = res.message;
			if (!id.value) {
				successId.value = res.data.id;
			} else {
				successId.value = id.value;
				eventChannel.value.emit('reloadPage', { reload: true });
			}
			show.value = true;
		}
		loading.value = false;
	}

	const id = ref('');
	onLoad(async (opt) => {
		if (opt.id) {
			uni.setNavigationBarTitle({
				title: '编辑报单'
			});
			loading.value = true
			id.value = opt.id;
			await getDetail();
		} else {
			isMount.value = true
		}
	});

	const isMount = ref(false)
	async function getDetail() {
		loading.value = true;
		const { success, data } = await fetchDetail(id.value).catch(() => {
			loading.value = false;
			isMount.value = true
		});
		if (success) {
			formData.value = data;
			loading.value = false;
		}
		isMount.value = true
	}

	onShareAppMessage(() => {
		return {
			title: '捷报Hub'
		}
	})
</script>

<style lang="scss" scoped>
	.fixed-bottom {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		width: 100%;
		background: #fff;
		z-index: 999;
	}

	.fui-ani__box {
		width: 640rpx;
		background: transparent;
		border-radius: 24rpx;
	}

	.fui-hd__img {
		width: 100%;
		display: block;
	}

	.fui-ani__title {
		font-size: 36rpx;
		font-weight: 600;
		padding: 54rpx 0 32rpx;
		text-align: center;
	}

	.fui-desc {
		padding: 0 54rpx 82rpx;
		font-size: 24rpx;
		line-height: 48rpx;
		font-weight: 400;
		color: #333333;
		box-sizing: border-box;
	}

	.fui-desc text {
		color: #ff2b2b;
	}

	.fui-flex__center {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		align-items: center;
		justify-content: center;
	}

	.fui-flex__column {
		flex-direction: column !important;
	}

	.fui-box-content {
		position: absolute;
		left: 0;
		right: 0;
		top: 300rpx;
	}
</style>